package com.aliyun.heiyu.powermaster.server.util;

import com.aliyun.heiyu.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Configuration {


private static Logger logger = LoggerFactory.getLogger(Configuration.class);
public static final String IP = getInet4Address();

private static Pattern PATTERN = Pattern.compile("inet addr:(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})");
/**
 * 获取本地IP
 * @return
 */
private static String getLocalIp() {

    //查询当前操作系统
    Properties p = System.getProperties();
    String osName = p.getProperty("os.name");

    try {
        //如果是windows
        if (osName.matches("(?i).*win.*")) {
            return InetAddress.getLocalHost().getHostAddress().toString();//获得本机IP
        } else {

            //根据"systeminfo"命令查询开机时间
            Process process = Runtime.getRuntime().exec("ifconfig");
            InputStream inputStream = process.getInputStream();
            String s = "";
            byte[] b = new byte[1024];
            while (inputStream.read(b) != -1) {
                s = s + new String(b);
            }
            if (!StringUtil.isEmpty(s)) {
                Matcher m = PATTERN.matcher(s);
                if (m.find()) {
                    process.destroy();
                    return m.group(1);
                }
            }
        }
    } catch (Exception e) {
        logger.error("获取ip地址异常", e);
    }
    return "127.0.0.1";
}


public static String getInet4Address() {
    Enumeration<NetworkInterface> nis;
    String ip = null;
    try {
        nis = NetworkInterface.getNetworkInterfaces();
        for (; nis.hasMoreElements(); ) {
            NetworkInterface ni = nis.nextElement();
            Enumeration<InetAddress> ias = ni.getInetAddresses();
            for (; ias.hasMoreElements(); ) {
                InetAddress ia = ias.nextElement();
                    if (ia instanceof Inet4Address && !ia.getHostAddress().equals("127.0.0.1")) {
                    ip = ia.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ip;

}




}
